package com.easybuilder.common.config.datasource;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.easybuilder.common.utils.FileUtil;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DataSourcePool {

    private static DataSource dataSource;

    //通过ThreadLocal存放连接，确保同一个事务中，使用的是同一个连接
    private static final ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    //加载数据库连接池配置
    static {
        Properties props = new Properties();
        try(
                InputStream is = FileUtil.getResourceStream("application.yml");
        ) {
            props.load(is);
            dataSource = DruidDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //手动从连接池获取连接
    public static Connection getConnection() {

        Connection conn = null;
        try {
            conn = threadLocal.get();
            if (null == conn || conn.isClosed()) {
                conn = dataSource.getConnection();
                threadLocal.set(conn);
            }
            //关闭自动提交事务
            //conn.setAutoCommit(false);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return conn;
    }

    //归还连接
    public static void returnConnection() {
        Connection conn = threadLocal.get();
        threadLocal.remove();
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

}
